// MQTT subscriber using mqtt_util module
#include "mqtt_client.h"
#include "app_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

static volatile int g_running = 1;

static void handle_sigint(int sig)
{
    (void)sig;
    g_running = 0;
}

static void on_conn(int rc, void *user)
{
    mqtt_client_t *cli = (mqtt_client_t*)user;
    (void)cli;
    if (rc == 0) {
        // subs restored automatically; nothing to do
        printf("Connected.\n");
    } else {
        fprintf(stderr, "Connect failed: rc=%d\n", rc);
    }
}

static void on_msg(const char *topic, const void *payload, int len, void *user)
{
    (void)user;
    printf("topic: %s\n", topic ? topic : "");
    printf("message (%d bytes): ", len);
    fwrite(payload, 1, (size_t)len, stdout);
    printf("\n");
}

int main(int argc, char *argv[])
{
    const char *host = (argc > 1) ? argv[1] : APPCFG_DEFAULT_MQTT_HOST;
    int port = (argc > 2) ? atoi(argv[2]) : APPCFG_DEFAULT_MQTT_PORT;
    const char *topic = (argc > 3) ? argv[3] : APPCFG_DEFAULT_SUB_TOPIC;

    signal(SIGINT, handle_sigint);

    mqtt_config_t cfg; mqtt_config_from_env(&cfg);
    cfg.host = host; cfg.port = port;
    if (!(getenv("MQTT_WS_ENABLE") && *getenv("MQTT_WS_ENABLE"))) cfg.ws_enable = APPCFG_DEFAULT_WS_ENABLE ? true : false;
    if (!(getenv("MQTT_TLS_ENABLE") && *getenv("MQTT_TLS_ENABLE"))) cfg.tls_enable = APPCFG_DEFAULT_TLS_ENABLE ? true : false;
    if (cfg.ws_enable && !(getenv("MQTT_WS_PATH") && *getenv("MQTT_WS_PATH"))) cfg.ws_path = APPCFG_DEFAULT_WS_PATH;
    mqtt_client_t *cli = mqtt_client_new(&cfg, NULL);
    if (!cli) { fprintf(stderr, "OOM\n"); return 1; }
    mqtt_client_set_message_cb(cli, on_msg);
    mqtt_client_set_connect_cb(cli, on_conn);

    int rc = mqtt_client_connect(cli);
    if (rc != 0) { fprintf(stderr, "connect error: %s (host=%s port=%d)\n", mqtt_errstr(rc), host, port); mqtt_client_destroy(cli); return 1; }
    mqtt_client_start(cli);
    if (mqtt_client_subscribe(cli, topic, 1) != 0) { fprintf(stderr, "subscribe failed: %s\n", topic); }

    printf("MQTT subscriber running. Broker=%s:%d, topic=%s\n", host, port, topic);
    while (g_running) sleep(1);

    mqtt_client_disconnect(cli);
    mqtt_client_stop(cli);
    mqtt_client_destroy(cli);
    return 0;
}
